package com.ruizhong.integratedmediawithoutc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruizhong.integratedmediawithoutc.config.DefaultAssetsPathProvider;
import com.ruizhong.integratedmediawithoutc.controller.SystemController;
import com.ruizhong.integratedmediawithoutc.dao.TMaterialMapper;
import com.ruizhong.integratedmediawithoutc.entity.TMaterial;
import com.ruizhong.integratedmediawithoutc.service.TMaterialService;
import com.ruizhong.integratedmediawithoutc.service.TProgramMaterialService;
import com.ruizhong.integratedmediawithoutc.util.FolderActivityMonitor;
import com.ruizhong.integratedmediawithoutc.util.H265ToH264Converter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class TMaterialServiceImpl extends ServiceImpl<TMaterialMapper, TMaterial> implements TMaterialService {

    @Autowired
    private DefaultAssetsPathProvider pathProvider;

    @Autowired
    private TProgramMaterialService tProgramMaterialService;

    @Override
    public List<TMaterial> getResourceList(String programType) {
        List<TMaterial> list = null;
        switch(programType){
            case "视频":
                list = lambdaQuery()
                        .eq(TMaterial::getMaterialType, 1)
                        .list();
                for (TMaterial tMaterial : list) {
                    tMaterial.setTotalMs(tMaterial.getDuration());
                }
                break;
            case "图片":
                list = lambdaQuery()
                    .eq(TMaterial::getMaterialType, 2)
                    .list();
                break;
            case "ppt":
                list = lambdaQuery()
                        .eq(TMaterial::getMaterialType, 3)
                        .list();
                break;
            default:
                list = list();
                break;
        }
        return list;
    }

    @Override
    public List<HashMap<String, String>> getMaterialList() {
        List<TMaterial> tMaterials = list();
        Set<String> resources = tMaterials.stream().map(new Function<TMaterial, String>() {
            @Override
            public String apply(TMaterial tMaterial) {
                return tMaterial.getFile().toString();

            }
        }).collect(Collectors.toSet());
        HashSet<String> fileNamesSet = FolderActivityMonitor.fileNamesSet;
        List<HashMap<String, String>> files =new ArrayList<>();
        fileNamesSet.forEach(new Consumer<String>() {
            @Override
            public void accept(String s) {
                if (!resources.contains(s)) {
                    HashMap<String, String> videoMap = new HashMap<>();
                    videoMap.put("file", s);
                    files.add(videoMap);
                }
            }
        });
        return files;
    }

    @Override
    public void addResources(Map<String, Object> conditionMap) throws IOException {
        String wsToken = conditionMap.get("wsToken").toString();
        ArrayList<HashMap<String, Object>> videoList =
                (ArrayList<HashMap<String, Object>>) conditionMap.get("data");
        for (HashMap<String, Object> videoInfo : videoList) {
            String fileName = videoInfo.get("file").toString();
            H265ToH264Converter.convertVideo(
                    SystemController.share_dir + "/" + fileName,
                    pathProvider.getCurrentAssetsPath() + fileName,
                    wsToken, this
            );
        }

    }

    @Override
    public void saveNewMaterial(long duration, String fileName,Integer materialType) {
        TMaterial tMaterial = new TMaterial();
        tMaterial.setDuration(duration);
        tMaterial.setFile(fileName);
        tMaterial.setMaterialType(materialType);
        // 定义日期时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();

        // 格式化日期时间
        String formattedDateTime = now.format(formatter);

        System.out.println("当前时间: " + formattedDateTime);
        tMaterial.setSubmitTime(formattedDateTime);
        save(tMaterial);
    }

    @Override
    @Transactional
    public void deleteResource(Map<String, Object> conditionMap) {
        ArrayList<HashMap<String, Object>> data = (ArrayList<HashMap<String, Object>>) conditionMap.get("data");
        String file_path = data.get(0).get("file_path").toString();
        QueryWrapper<TMaterial> tMaterialQueryWrapper = new QueryWrapper<>();
        tMaterialQueryWrapper.lambda().eq(TMaterial::getFile,file_path);
        remove(tMaterialQueryWrapper);
        new Thread(new Runnable() {
            @Override
            public void run() {
                File file = new File(pathProvider.getCurrentAssetsPath()+"/"+file_path);
                if (file.delete()) {
                    System.out.println("文件删除成功");
                } else {
                    System.out.println("文件删除失败");
                }
            }
        }).start();
        tProgramMaterialService.deleteByFileName(file_path);
        System.out.println(conditionMap);
    }

    @Override
    public void deleteAllResources() {
        List<TMaterial> list = list();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (TMaterial tMaterial : list) {
                    File file = new File(pathProvider.getCurrentAssetsPath() + "/" + tMaterial.getFile());
                    if (file.delete()) {
                        System.out.println("文件删除成功");
                    } else {
                        System.out.println("文件删除失败");
                    }
                }
            }
        }).start();
        remove(null);
    }
}
